package com.ruoyi.deeplearn.component;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.http.OkHttpUtils;
import com.ruoyi.deeplearn.component.modelVo.PyDeployModeVo;
import com.ruoyi.deeplearn.component.modelVo.PyDeployModelSetWorkerVo;
import com.ruoyi.deeplearn.component.modelVo.PyDeployModelRegisteVo;
import com.ruoyi.deeplearn.domain.DeepAlgorithm;
import com.ruoyi.deeplearn.domain.DeepModelDeploy;
import com.ruoyi.deeplearn.domain.DeepModelVersion;
import com.ruoyi.deeplearn.service.*;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ModelDeployComponent {
    @Autowired
    private IDeepForecastService deepForecastService;
    @Autowired
    private IDeepAlgorithmService deepAlgorithmService;
    @Autowired
    private IDeepModelVersionService deepModelVersionService;
    @Autowired
    private IDeepModelService deepModelService;
    @Autowired
    private IDeepModelDeployService deepModelDeployService;



    public void publishDeploy(Long modelDeployId) {
        DeepModelDeploy modelDeploy = deepModelDeployService.selectDeepModelDeployById(modelDeployId);
        if(modelDeploy==null)return;
        DeepModelVersion modelVersion = deepModelVersionService.selectDeepModelVersionById(modelDeploy.getModelVersionId());
        if(modelVersion==null)return;
//        DeepAlgorithm deepAlgorithm = deepAlgorithmService.selectDeepAlgorithmById(modelVersion.getTrainAlgorithmId());
//        if(deepAlgorithm==null)return;
//        if(deepAlgorithm.getPlatform()==2){//pytorch
//            publishDeployByPyTorch(modelDeploy,modelVersion,deepAlgorithm);
//        }
    }

    /**
     * 注册新模型
     * curl -X POST "http://121.36.8.195:8081/models?url=fastrcnn.mar"
     * 分配进程数worker
     * curl -X PUT "http://121.36.8.195:8081/models/fastrcnn?min_worker=1"
     * 查看fastcnn模型注册情况
     * curl "http://121.36.8.195:8081/models/fastrcnn"
     * @param modelDeploy
     * @param modelVersion
     * @param deepAlgorithm
     */
    private void publishDeployByPyTorch(DeepModelDeploy modelDeploy,
                                        DeepModelVersion modelVersion,
                                        DeepAlgorithm deepAlgorithm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                processPyRegister(modelDeploy,modelVersion,deepAlgorithm);
            }
        }).start();
    }

    //注册模型
    private void processPyRegister(DeepModelDeploy modelDeploy,
                                   DeepModelVersion modelVersion,
                                   DeepAlgorithm deepAlgorithm) {
        //注册新模型
        Map<String, String> body = new HashMap<>();
        //url参数可以是一个远程地址，eg: curl -X POST  "http://localhost:8081/models?url=https://torchserve.pytorch.org/mar_files/squeezenet1_1.mar"
        body.put("url",deepAlgorithm.getCode()+".mar");//
        //curl -X POST "http://121.36.8.195:8081/models?url=fastrcnn.mar"
        OkHttpUtils.getInstance().init()
                .url(deepAlgorithm.getModelUrl()+"/models?url="+deepAlgorithm.getCode()+".mar")
                .formBodyPost(body).exec(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            if(response.isSuccessful()){
                                PyDeployModelRegisteVo modelVo = JSON.parseObject(response.body().string(), PyDeployModelRegisteVo.class);
                                if(modelVo!=null){
                                    //
//                                    modelVersion.setDeployStatus(DeepModelVersion.deploy_publish);
                                    deepModelVersionService.updateDeepModelVersion(modelVersion);
                                }
                                //设置工作线程
                                processPySetWorker(modelDeploy,modelVersion,deepAlgorithm);
                            }else {
                                //网络异常
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    //设置模型工作线程数
    private void processPySetWorker(DeepModelDeploy modelDeploy,
                                    DeepModelVersion modelVersion, DeepAlgorithm deepAlgorithm) {
        Map<String, String> body = new HashMap<>();
        body.put("min_worker","2");
        //curl -X PUT "http://121.36.8.195:8081/models/fastrcnn?min_worker=1"
        OkHttpUtils.getInstance().init()
                .url(deepAlgorithm.getModelUrl()+"/models/"+deepAlgorithm.getCode())
                .formBodyPut(body).exec(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            if(response.isSuccessful()){
                                PyDeployModelSetWorkerVo modelVo = JSON.parseObject(response.body().string(),PyDeployModelSetWorkerVo.class);
                                //获取信息
                                processPyGetModelInfo(modelDeploy,modelVersion,deepAlgorithm);
                            }else {
                                //网络异常
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
    }

    //获取模型信息
    private void processPyGetModelInfo(DeepModelDeploy modelDeploy,
                                    DeepModelVersion modelVersion, DeepAlgorithm deepAlgorithm) {

        //curl "http://121.36.8.195:8081/models/fastrcnn"
        OkHttpUtils.getInstance().init()
                .url(deepAlgorithm.getModelUrl()+"/models/"+deepAlgorithm.getCode())
                .get().exec(new OkHttpUtils.OnResponse() {
                    @Override
                    public void onSuccess(Response response) {
                        try {
                            if(response.isSuccessful()){
                                String str = response.body().string();
                                List<PyDeployModeVo> modeVos = JSON.parseArray(str,PyDeployModeVo.class);
                                if(modeVos!=null){

                                }
                            }else {
                                //网络异常
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        e.printStackTrace();
                    }
                });
    }
}
